//
//  RHToViewPhotosVC.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/10/1.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit

class RHToViewPhotosVC: RHViewController, UIScrollViewDelegate {
    var scrollView = UIScrollView()
    var pageControl = UIPageControl()
    let width = UIScreen.main.bounds.size.width
    let height = UIScreen.main.bounds.size.height
    var imageArray : NSMutableArray?

    var index = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        loadScrollView()
        loadPageControl()
    }
    
    func loadPageControl(){
        self.view.addSubview(pageControl)
        pageControl.snp.makeConstraints({(make) in
            make.top.equalTo(height - 20)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.width.equalTo(width)
            make.height.equalTo(20)
        })
        
        pageControl.numberOfPages = (imageArray?.count)!
        pageControl.currentPage = index
        pageControl.currentPageIndicatorTintColor = UIColor.white
        pageControl.pageIndicatorTintColor = UIColor.gray
    }
    
    func loadScrollView(){
        self.view.addSubview(scrollView)
        scrollView.isPagingEnabled = true
        scrollView.scrollsToTop = true
        scrollView.bounces = true
        scrollView.delegate = self
        
        var i = 0
        scrollView.snp.makeConstraints({(make) in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.right.equalTo(0)
            make.width.equalTo(width)
            make.height.equalTo(height)
        })
        
        for _ in imageArray! {
            let imageView = UIImageView()
            imageView.image = imageArray?[i] as? UIImage
            imageView.backgroundColor = UIColor.black
            imageView.contentMode = .scaleAspectFit
            scrollView.addSubview(imageView)
            imageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(tapClick)))
            imageView.isUserInteractionEnabled = true

            imageView.snp.makeConstraints({(make) in
                make.top.equalTo(0)
                make.left.equalTo(Int(width) * i)
                make.width.equalTo(width)
                make.height.equalTo(height)
            })
            i += 1
        }
        scrollView.contentSize = CGSize(width: Int(width) * (imageArray?.count)!, height: Int(height))
        scrollView.contentOffset = CGPoint(x: index == 0 ? 0 : index * Int(width), y: Int(height))
    }
    
    @objc func tapClick() {
        self.dismiss(animated: false, completion: nil)
    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        let offset = scrollView.contentOffset.x / width
        pageControl.currentPage = Int(offset)
    }
}
